package com.ity.teamanagement.utils;

import com.ity.teamanagement.code.CommonCode;
import com.ity.teamanagement.code.UserCode;
import com.ity.teamanagement.entity.outputResult.UserDetail;
import com.ity.teamanagement.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author coderFu
 * @create 2021/5/23
 */
@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate redisTemplate;



    /**
     * 从token中获取用户信息
     * @param request
     * @return
     */
    public UserDetail getHeader(HttpServletRequest request){
        String header = request.getHeader("Set-Cookie");
        System.out.println(header);
        if (StringUtils.isBlank(header)){
            ExceptionUtils.error(UserCode.USER_NOT_LOGIN);
        }
        if (redisTemplate.hasKey(header)){
            UserDetail userDetail = (UserDetail) redisTemplate.opsForValue().get(header);
            return userDetail;
        }
        ExceptionUtils.error(CommonCode.TOKEN_ERROR);
        return null;
    }


    public void checkAuthorityStatus(HttpServletRequest request){
        String header =  request.getHeader("Set-Cookie");
        if (StringUtils.isBlank(header)){
            ExceptionUtils.error(UserCode.USER_NOT_LOGIN);
        }
        if (!redisTemplate.hasKey(header)){
            ExceptionUtils.error(UserCode.USER_NOT_LOGIN);
        }
        UserDetail user = getHeader(request);
        if (user.getUserRole() != 1){
            ExceptionUtils.error(UserCode.USER_AUTH_ERROR);
        }
    }

    public void checkLoginState(HttpServletRequest request){
        String header =  request.getHeader("Set-Cookie");
        if (StringUtils.isBlank(header)){
            ExceptionUtils.error(UserCode.USER_NOT_LOGIN);
        }
        if (!redisTemplate.hasKey(header)){
            ExceptionUtils.error(UserCode.USER_NOT_LOGIN);
        }
    }
}
